<template>
  <div class="address-container">
    <nav-bar>
      <div class="left" slot="left"  @click="goBack()">
        <i class="iconfont icon-fanhui"></i>
      </div>
      <div slot="center">修改地址</div>
    </nav-bar>
    <div class="address-content">
      <van-address-edit
          :address-info="addressInfo"
          :area-list="areaList"
          show-postal
          show-delete
          show-set-default
          show-search-result
          :area-columns-placeholder="['请选择', '请选择', '请选择']"
          @save="onSave"
      />
    </div>
  </div>
</template>

<script>
import NavBar from '../../components/nav-bar/Nav-Bar'
import { areaList } from '@vant/area-data';
import {changeAddress,getAddressDetail} from "../../api/profile/profile";
// import {addressCode} from "../../utils/address";
import {Toast} from "vant";
export default {
  name: "addAddress",
  components: {
    NavBar
  },
  data() {
    return {
      areaList,
      addressInfo:{},
      addressId:0
    }
  },
  activated() {
    let address = this.$route.params.addressInfo
    this.addressId = address.id
    this.getAddressDetailData()
    // this.addressInfo = {
    //   addressDetail: address.address,
    //   city:address.city,
    //   country:address.country,
    //   county:address.county,
    //   isDefault: false,
    //   name:address.name,
    //   postalCode:address.postalCode,
    //   province:address.province,
    //   tel:address.phone,
    //   id:address.id
    // }
  },
  methods:{
    goBack(){
      this.$router.go(-1)
    },
    // 获取地址详情
    async getAddressDetailData(){
      const res = await getAddressDetail(this.addressId)
      let data = res.data
      // let province
      // let key1 = ''
      // addressCode.forEach((item)=>{
      //     if(item[key1] === data.province){
      //       province = key1
      //     }
      //
      // })
      this.addressInfo = {
        name:data.name,
        tel:data.phone,
        addressDetail:data.address,
        isDefault:data.is_default === 1,
        postalCode:'020301',
        areaCode:'110107',
        city:data.city,
        county:data.county

      }
      console.log(data);
    },

    async onSave(content){
      let addressInfo = {
        name:content.name,
        address:content.addressDetail,
        phone:content.tel,
        province:content.province,
        city:content.city,
        county:content.county,
        is_default:content.isDefault ? 1 : 0
      }
      const res = await changeAddress(this.addressId,addressInfo)
      if(res.status === 204){
        Toast.success('修改成功')
        await this.$router.push({path: '/addressList'})
      }
      // console.log(content);
    }
  }
}
</script>

<style scoped lang="css">
.address-container{
  padding-top: 45px;
}
.left{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.iconfont{
  font-size: 24px;
}
.van-button--danger{
  background-color: #42bBaa !important;
  border: none;
}
</style>